package com.bml.client.secret.demo;

import ch.ethz.ssh2.Session;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author: baiml
 * @Title: ShellTest
 * @ProjectName: 海联技术平台
 * @Depart 软件事业部
 * @Description:
 * @date: 2021/9/17 11:23
 */
public class ShellTest2 {

    public static void main(String[] args) throws Exception {

        System.out.println(String.format("if [ ! -x %s ]; then","/opt/test/dev"));

        boolean ismodify =true;
        RemoteShellExecutor executor = new RemoteShellExecutor("192.168.10.205", "root", "hirisun123");

        StringBuilder builder = new StringBuilder();
        builder.append("#!/bin/sh").append("\n");
        builder.append("if [ ! -x /opt/test/dev ]; then").append("\n");
        builder.append("mkdir -p /opt/test/dev ").append("\n");
        builder.append("fi").append("\n");
        builder.append("echo remote dir create success!");
        System.out.println(builder.toString());
        int exec = executor.exec(builder.toString(), new ShellCallBack() {
            @Override
            public void doWith(Session session) {
                try (InputStream stdout = session.getStdout()) {
                    BufferedReader br = new BufferedReader(new InputStreamReader(stdout, "utf-8"));
                    String line = null;
                    while((line = br.readLine()) != null){
                        System.out.println(getDateFormat() +line);
                    }
                } catch (Exception ce) {
                    ce.printStackTrace();
                }
            }
        });
        System.out.println("return="+exec);
    }
    private static String getDateFormat() {
        return "[" + format(new Date(),"yyyy-MM-dd HH:mm:ss.SSS") + "]:";
    }
    public static String format(Date date, String format) {
        return format(date2LocalDateTime(date), format);
    }
    private static LocalDateTime date2LocalDateTime(Date date) {
        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    }
    public static String format(LocalDateTime localDateTime, String format) {
        return localDateTime.format(DateTimeFormatter.ofPattern(format));
    }


}
